package logic

import (
	"context"
	"errors"
	"home-view/homerpc/homerpc"
	"home-view/homerpc/internal/svc"
	"home-view/models/cache"
	"home-view/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *homerpc.LoginRequest) (*homerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if in.TypeLogin == 1 || in.TypeLogin == 2 {
		if err := user.FindUserByPhone(mysql.DB, in.Phone); err != nil {
			return nil, err
		}
		if user.ID == 0 {
			return nil, errors.New("手机号不存在")
		}
		if in.TypeLogin == 1 {
			if in.Password != user.Password {
				return nil, errors.New("密码错误")
			}
		}
		if in.TypeLogin == 2 {
			result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
			if result == "" {
				return nil, errors.New("你还没发送验证码")
			}
			if result != in.SendSmsCode {
				return nil, errors.New("验证码错误")
			}
		}
	}

	return &homerpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
